<template>
    <div class="searchHeader">
      <van-search
        shape="round"
        class="search"
        v-model="keyword"
        :placeholder="keyword"
        @search="toSearchGoodsList(keyword)"
        :onUpdate:modelValue="debounce"
      />
      <span @click="toHome">取消</span>
    </div>

    <router-view @getRealKeyword="getRealKeyword" :keyword="keyword" :realTimeKeywordList="realTimeKeywordList" @getKwdArr="getKwdArr"  @getKeyword="getKeyword"></router-view>
</template>

<script setup lang="ts">
  import { onUnmounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import searchApi from '@/api/search'
  import * as _ from 'lodash'
  
  
  const router = useRouter()
  const getKeyword = (val:string) => {
    keyword.value = val
  }
  
  const keyword = ref('')
  // 存储搜索记录
  const keyArr = ref<string[]>([])
  const toSearchGoodsList = (keyword:string) => {
    keyArr.value.push(keyword as any)
    localStorage.setItem('key',JSON.stringify(keyArr.value))
    router.push(`/search/searchGoodsList?keyword=${keyword}`)
  }

  const getKwdArr = (val:[]) => {
    keyArr.value = val
  }


// 用于存储实时获取到的搜索数据
const realTimeKeywordList = ref([])
// 实时搜索
const getRealTimeData = async ()=>{
    try {
     let res = await searchApi.getRealTimeKeywordList(keyword.value)
      // console.log('获取到的实时搜索数据',res.data);
     
     realTimeKeywordList.value = res.data
    } catch (error) {
     
    }
}

// 当输入是触发的函数
const inputHandler = ()=>{
  // console.log('触发了');
  localStorage.setItem('keywordPrefix',keyword.value)
  getRealTimeData()
}
const debounce = _.debounce(inputHandler, 300, {
      leading: true,  // 延长开始后调用
      trailing: true  // 延长结束前调用
    })


  // 获取列表里的关键字
  const getRealKeyword = (val : string) => {
    // console.log('val',val);
    keyword.value = val
  }

  // 点击取消返回首页
  const toHome = () => {
    router.push('/')
  }

onUnmounted(()=>{
  localStorage.removeItem('keywordPrefix')
  
})

</script>

<style scoped>
.searchHeader {
  display: flex;
  border-bottom: .03rem solid #eee;
}
.searchHeader span {
  font-size: .43rem;
  line-height: 1.5rem;
  margin-left: .13rem;
}
.searchHeader .search{
  width: 8.5rem;
}
</style>